const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require('path');
const BannerController = require("../controllers/bannerController");
const { verifyToken } = require("../middleware/auth");

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, 'banner-' + uniqueSuffix + path.extname(file.originalname))
  }
})

const upload = multer({ 
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    console.log('File type:', file.mimetype)    
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true)
    } else {
      cb(new Error('只允许上传jpg、png或gif格式的图片'), false)
    }
  }
})
// 公开接口
router.get("/page", BannerController.getBannersByPage);
router.get("/", BannerController.getAllBanners);
router.get("/:id", BannerController.getBannerById);

// 需要管理员权限的接口
router.post("/", verifyToken, upload.single('image'), BannerController.createBanner);
router.put("/:id", verifyToken, upload.single('image'), BannerController.updateBanner);
router.delete("/:id", verifyToken, BannerController.deleteBanner);
// 修改上传路由字段名为'file'
router.post("/upload", verifyToken, upload.single('file'), BannerController.uploadBannerImage);

module.exports = router;
